package com.yy.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;

/**
 * 对称加密 AES
 * @Author: lyy
 * Date: 2021/12/14 16:47
 */
public class AesUtil {
	/**
	 * 密钥，AES加密要求key必须为128 bit，否则会报错
	 */
	private static final String KEY = "1234567812345678";

	/**
	 * 加解密算法/模式/填充方式
	 * ECB模式只用密钥即可对数据进行加密解密，CBC模式需要添加一个iv
	 */
	private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

	private static final String AES = "AES";

	public static void main(String[] args) throws Exception {
		String content = "test中文";
		String result = encrypt(content, KEY);
		System.out.println(result);
		System.out.println(decrypt(result, KEY));
	}

	/**
	 * 加密
	 * @param content
	 * @param encryptKey
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String content, String encryptKey) throws Exception {
		byte[] bytes = encryptToBytes(content, encryptKey);
		return toHexString(bytes);
	}

	/**
	 * 解密
	 * @param encryptStr
	 * @param decryptKey
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptStr, String decryptKey) throws Exception {
		return decryptByBytes(convertHexString(encryptStr), decryptKey);
	}

	private static byte[] encryptToBytes(String content, String encryptKey) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), AES));
		return cipher.doFinal(content.getBytes(StandardCharsets.UTF_8));
	}

	private static String decryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
		Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), AES));
	    byte[] decryptBytes = cipher.doFinal(encryptBytes);
	    return new String(decryptBytes);
	}

	/**
	 * 解密Hex（16进制）或Base64表示的字符串
	 * @param ss
	 * @return
	 */
	private static byte[] convertHexString(String ss) {
		byte digest[] = new byte[ss.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = ss.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}
		return digest;
	}

	/**
	 * 将字节数组转换为十六进制字符串
	 * @param bytes
	 * @return
	 */
	private static String toHexString(byte[] bytes) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			String plainText = Integer.toHexString(0xff & bytes[i]);
			if (plainText.length() < 2) {
				plainText = "0" + plainText;
			}
			hexString.append(plainText);
		}
		return hexString.toString();
	}

}
